#include "mystdio.h"

myFILE *MyFopen(const char *fileName, const char *mode)
{
    int flags = 0;
    mode_t permission = 0666;
    int isCreate = 0;
    if (strcmp(mode, "r") == 0)
    {
        flags = O_RDONLY;
    }
    else if (strcmp(mode, "w") == 0)
    {
        flags = O_WRONLY | O_CREAT | O_TRUNC;
        isCreate = 1;
    }
    else if (strcmp(mode, "a") == 0)
    {
        isCreate = 1;
        flags = O_WRONLY | O_CREAT | O_APPEND;
    }
    else
    {
        return NULL;
    }
    int fd = isCreate == 1 ? open(fileName, flags, permission) : open(fileName, flags);
    if (fd < 0) return NULL;

    myFILE* fp = (myFILE*)malloc(sizeof(myFILE));
    if (!fp) return NULL;

    fp->_fileno = fd;
    fp->pos = 0;
    fp->_flags = flags;
    fp->_flushtype = FLUSH_LINE;
    return fp;
}
void MyFflush(myFILE * fp)
{
    write(fp->_fileno, fp->_buff, strlen(fp->_buff));
    fp->pos = 0;
}
void  MyFclose(myFILE *fp)
{
    MyFflush(fp);
    close(fp->_fileno);
    free(fp);
}
size_t MyFwrite(void* ptr[],size_t size, size_t nmemb, myFILE *fp)
{
    int n = size*nmemb;
    memmove(fp->_buff + fp->pos, ptr, n);

    if ((fp->_flushtype & FLUSH_LINE) && fp->_buff[fp->pos-1] == '\n')
    {
        MyFflush(fp);
    }
    return n;
}